package com.xjcs.saplingplan.utils

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.widget.Toast
import com.tencent.connect.UserInfo
import com.tencent.connect.share.QQShare
import com.tencent.connect.share.QzoneShare
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage
import com.tencent.mm.opensdk.modelmsg.WXTextObject
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.tencent.tauth.IUiListener
import com.tencent.tauth.Tencent
import com.tencent.tauth.UiError
import org.json.JSONException
import org.json.JSONObject

object ThirdPartyUtils {
    private const val QQ_APP_ID = "你的QQ_APP_ID"
    private const val WX_APP_ID = "你的微信APP_ID"

    private var mTencent: Tencent? = null
    private var mWxApi: IWXAPI? = null

    /**
     * 初始化三方SDK
     * @param context 上下文
     */
    fun init(context: Context?) {
        // 初始化QQ SDK
        mTencent = Tencent.createInstance(QQ_APP_ID, context)


        // 初始化微信SDK
        mWxApi = WXAPIFactory.createWXAPI(context, WX_APP_ID, true)
        mWxApi?.registerApp(WX_APP_ID)
    }

    /**
     * QQ登录
     * @param activity 活动上下文
     * @param listener 登录回调监听器
     */
    fun qqLogin(activity: Activity?, listener: QQLoginListener) {
        if (!mTencent!!.isSessionValid) {
            mTencent!!.login(activity, "all", object : IUiListener {
                override fun onComplete(o: Any) {
                    try {
                        val jsonObject = o as JSONObject
                        val openId = jsonObject.getString("openid")
                        val accessToken = jsonObject.getString("access_token")
                        val expiresIn = jsonObject.getLong("expires_in")

                        mTencent!!.openId = openId
                        mTencent!!.setAccessToken(accessToken, expiresIn.toString() + "")


                        // 获取用户信息
                        val qqToken = mTencent!!.qqToken
                        val userInfo = UserInfo(activity, qqToken)
                        userInfo.getUserInfo(object : IUiListener {
                            override fun onComplete(o: Any) {
                                listener.onComplete(o)
                            }

                            override fun onError(uiError: UiError) {
                                listener.onError(uiError)
                            }

                            override fun onCancel() {
                                listener.onCancel()
                            }

                            override fun onWarning(i: Int) {}
                        })
                    } catch (e: JSONException) {
                        e.printStackTrace()
                        listener.onError(UiError(-1, "数据解析错误", null))
                    }
                }

                override fun onError(uiError: UiError) {
                    listener.onError(uiError)
                }

                override fun onCancel() {
                    listener.onCancel()
                }

                override fun onWarning(i: Int) {}
            })
        } else {
            Toast.makeText(activity, "已登录", Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 微信登录
     * @param activity 活动上下文
     * @param listener 登录回调监听器
     */
    fun wxLogin(activity: Activity?, listener: WXLoginListener) {
        if (!mWxApi!!.isWXAppInstalled) {
            Toast.makeText(activity, "未安装微信", Toast.LENGTH_SHORT).show()
            return
        }


        // 微信登录需要通过微信的AuthActivity实现
        // 这里需要你实现WXEntryActivity来处理回调
        // 实际登录逻辑应该在WXEntryActivity中处理
        listener.onStartAuth()
    }

    /**
     * QQ分享到好友
     * @param activity 活动上下文
     * @param title 标题
     * @param summary 摘要
     * @param targetUrl 跳转链接
     * @param imageUrl 图片链接
     */
    fun shareToQQ(
        activity: Activity?, title: String?, summary: String?,
        targetUrl: String?, imageUrl: String?
    ) {
        val params = Bundle()
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT)
        params.putString(QQShare.SHARE_TO_QQ_TITLE, title)
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, summary)
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, targetUrl)
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, imageUrl)

        mTencent!!.shareToQQ(activity, params, BaseUiListener())
    }

    /**
     * QQ分享到空间
     * @param activity 活动上下文
     * @param title 标题
     * @param summary 摘要
     * @param targetUrl 跳转链接
     * @param imageUrls 图片链接集合
     */
    fun shareToQZone(
        activity: Activity?, title: String?, summary: String?,
        targetUrl: String?, imageUrls: ArrayList<String?>?
    ) {
        val params = Bundle()
        params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT)
        params.putString(QzoneShare.SHARE_TO_QQ_TITLE, title)
        params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, summary)
        params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, targetUrl)
        params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, imageUrls)

        mTencent!!.shareToQzone(activity, params, BaseUiListener())
    }

    /**
     * 微信分享文本
     * @param text 分享文本
     * @param isTimeline 是否分享到朋友圈
     */
    fun wxShareText(text: String?, isTimeline: Boolean) {
        if (TextUtils.isEmpty(text)) {
            return
        }

        val textObj = WXTextObject()
        textObj.text = text

        val msg = WXMediaMessage()
        msg.mediaObject = textObj
        msg.description = text

        val req = SendMessageToWX.Req()
        req.message = msg
        req.scene =
            if (isTimeline) SendMessageToWX.Req.WXSceneTimeline else SendMessageToWX.Req.WXSceneSession

        mWxApi!!.sendReq(req)
    }

    /**
     * 微信分享网页
     * @param webpageUrl 网页链接
     * @param title 标题
     * @param description 描述
     * @param thumbData 缩略图数据
     * @param isTimeline 是否分享到朋友圈
     */
    fun wxShareWebpage(
        webpageUrl: String?, title: String?,
        description: String?, thumbData: ByteArray?, isTimeline: Boolean
    ) {
        val webpage = WXWebpageObject()
        webpage.webpageUrl = webpageUrl

        val msg = WXMediaMessage(webpage)
        msg.title = title
        msg.description = description
        msg.thumbData = thumbData

        val req = SendMessageToWX.Req()
        req.message = msg
        req.scene =
            if (isTimeline) SendMessageToWX.Req.WXSceneTimeline else SendMessageToWX.Req.WXSceneSession

        mWxApi!!.sendReq(req)
    }

    /**
     * 处理Activity结果
     * @param requestCode 请求码
     * @param resultCode 结果码
     * @param data 数据
     */
    /*fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (mTencent != null) {
            mTencent.onActivityResultData(requestCode, resultCode, data)
        }
    }*/

    // QQ登录回调监听器
    interface QQLoginListener {
        fun onComplete(response: Any?)
        fun onError(error: UiError?)
        fun onCancel()
    }

    // 微信登录回调监听器
    interface WXLoginListener {
        fun onStartAuth()
        fun onComplete(code: String?)
        fun onError(error: String?)
        fun onCancel()
    }

    // 基础UI监听器
    private class BaseUiListener : IUiListener {
        override fun onComplete(o: Any) {
            // 分享成功
        }

        override fun onError(uiError: UiError) {
            // 分享失败
        }

        override fun onCancel() {
            // 取消分享
        }

        override fun onWarning(i: Int) {
        }
    }
}